package com.example.pro3_reactor;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.SignalType;

/**
 * @program: reactivePro
 * @description: 错误 处理
 * @author: zy
 * @create: 2025-04-26 21:17
 */
public class App7_onErrorReturn {
    public static void main(String[] args) {
        // 发生错误时返回默认值
        Flux.just(1, 2, 0, 4)
                .map(i -> "100 / " + i + " = " + (100 / i))
                .onErrorReturn("Divided by zero :")
                .subscribe(System.out::println);
        System.out.println("=======================================");

        //onErrorResume - 发生错误时切换到一个备用的 Publisher
        Flux.just(10,20,30,0,40,50)
                .map(i->100/i)
                .onErrorResume((t)->{
                    if(t instanceof ArithmeticException){
                        return Flux.just(99,100,101);
                    }
                    return Mono.error(t);
                })
                .subscribe(System.out::println);

        System.out.println("=======================================");
        //onErrorComplete() 用于捕获并消化异常：
        Flux.just(10,20,30,0,40,50)
                .map(i->100/i)
                .onErrorComplete(e->{
                    System.out.println("e = " + e);
                    return true;
                })
                .subscribe(System.out::println);
        System.out.println("=======================================");

        //doFinally 最终完成执行的方法, 参数 type 表示状态类型(取消,完成,错误)
        Flux.just("fish", "bird", "cat", "dog")
                .doOnSubscribe(s -> System.out.println("=== begin " + System.currentTimeMillis()))
                .doFinally(type -> {
                    System.out.println("=== type " + type);
                    if (type == SignalType.CANCEL) {
                        System.out.println("=== end   " + System.currentTimeMillis());
                    }
                })
                .take(3)
                .subscribe(System.out::println);

    }
}
